package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    //注册功能
    public void reg(User user) {
        //通过user参数来获取传递过来的username
        String username = user.getUsername();
        //调用findByUserName（username）判断用户是否被注册过
        User result = userMapper.findByUsername(username);
        //判断结果集是否不为null则抛出用户名被占用的异常
        if(result != null)
        {
            //抛出异常
            throw new UsernameDuplicatedException("用户名被占用");
        }

        //密码的机密处理：md5算法的形式67dhdsgh-ueuwrey121-urilji3447-sdasdjaks-651321
        //串+passw+串 ---- md5算法进行加密,连续加载三次
        //盐值+passw+盐值 --- 盐值就是一个随机的字符串
        String oldPassword = user.getPassword();
        //获取盐值（字符串）
        String salt = UUID.randomUUID().toString().toUpperCase();
        //补全数据：盐值的记录
        user.setSalt(salt);
        String md5Password = getMD5Password(oldPassword,salt);
        user.setPassword(md5Password);

        //补全数据:
        // is_delete设置成0
        user.setIs_Delete(0);
        // 4个字段的信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        //执行注册业务功能的实现
        Integer rows = userMapper.insert(user);
        if(rows != 1)
        {
            throw new InsertExcption("在用户注册过程中产生了未知的异常");
        }
    }

    @Override
    //登陆功能
    public User login(String username, String password) {
        //根据用户名称来查询用户的数据是否存在，如果不存在则抛出异常
        User result = userMapper.findByUsername(username);
        if(result == null)
        throw new UserNotFoundException("用户数据不存在");
        //检测用户的密码是否匹配
        //1.先获取到数据库中的加密之后的密码
        String oldPassword = result.getPassword();
        //2.和用户的传递过来的密码进行比较
        //2.1先获取盐值：上一次注册是所自动生成的盐值
        String salt = result.getSalt();
        //2.2将用户的密码按照相同的MD5算法的规则进行加密
        String newMd5Password = getMD5Password(password,salt);
        //3.将密码进行比较
        if(!newMd5Password.equals(oldPassword))
        {
            throw new PasswordNotMatchException("用户密码错误");
        }

        //判断id_delete字段是否为1 表示被标为删除
        if(result.getIs_Delete()==1)
        {
            throw new UserNotFoundException("用户数据不存在");
        }
        //调用mapper中findByUsername来查询用户的数据
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());
        //拿一点数据需要的数据就行，来查询用户的数据提升系统的性能


        //将当前的用户数据返回，返回的数据是为了辅助其他页面做数据的展示如名字，头像
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIs_Delete()==1 )
        {
            throw  new UserNotFoundException("用户数据不存在");
        }
        //原始密码和数据库中密码进行比较
        String oldMd5Password = getMD5Password(oldPassword,result.getSalt());
        if(!result.getPassword().equals(oldMd5Password))
        {
            throw new PasswordNotMatchException("密码错误");
        }
        //将新的密码设置到数据库中，将新的密码加密再更新到数据库中
        String newMd5Password = getMD5Password(newPassword,result.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid,newMd5Password,username,new Date());
        if (rows != 1)
        {
            throw new Updateexception("更新数据产生未知的异常");
        }
    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if(result == null||result.getIs_Delete() == 1)
        {
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());
        return user;
    }

    @Override
    public void changeInfo(Integer uid, String usernaem, User user) {
        User result = userMapper.findByUid(uid);
        if(result==null||result.getIs_Delete()==1)
        {
            throw new UserNotFoundException("用户数据不存在");
        }
        user.setUid(uid);
        //user.setUsername(usernaem);
        user.setModifiedUser(usernaem);
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if(rows!=1)
        {
            throw new Updateexception("更新数据时产生未知异常");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        //查询当前的用户数数据是否存在
        User result = userMapper.findByUid(uid);
        if(result==null||result.getIs_Delete()==1)
        {
            throw new UserNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid,avatar,username,new Date());
        if (rows !=1)
        {
         throw new Updateexception("更新用户头像产生未知的异常");
        }
    }


    /** 定义一个md5算法的加密处理**/
    private String getMD5Password(String password,String salt)
    {
        for(int i = 0;i < 3;i++) {
            //md5加密算法的调用(进行三次加密)
          password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}

